﻿var controller = this.lookupController();
var status = controller.analysis().status;
var ukCrossCharge = ref.UKCrossCharge.getValue();

controller.balance = controller.balance || {};
controller.budgetControl = controller.budgetControl || {};

if (status == 'launch' || status == 'resubmit') {
    var record = store.getUpdatedRecords()[0],
        flag = 'update';
    if (!record) {
        record = store.getNewRecords()[0];
        flag = 'add';
    }
    if (!record) {
        flag = 'reset';
    }
    if (record) {
        var grid3 = ref.datagrid3,
            editor3 = grid3.getColumns()[0].getEditor();

        var grid4 = ref.datagrid4,
            editor4 = grid4.getColumns()[0].getEditor();
        var grid6 = ref.datagrid6,
            editor6 = grid6.getColumns()[0].getEditor();
        var horizonGrid = ref.horizonGrid,
            horizonEditor = horizonGrid.getColumns()[0].getEditor();

        controller.getBalance(record.get('ProjectActivity'));

        if (flag == 'update') {
            if (record.modified) {
                if (record.modified.DescriptionOfSuppliesServices !== undefined) {
                    if (!Ext.isEmpty(record.data.DescriptionOfSuppliesServices)) {
                        if (record.data.DescriptionOfSuppliesServices.length > 200) {
                            controller.showMsgTips('Maximum 200 characters are allowed.');

                            record.data.DescriptionOfSuppliesServices = record.previousValues.DescriptionOfSuppliesServices;
                        }

                        var store = ref.datagrid7.getStore();
                        var count = 0;
                        for (var i = 0; i < store.getCount(); i++) {
                            var descriptionOfSuppliesServiceInfo = store.getAt(i).data.DescriptionOfSuppliesServices;
                            if (descriptionOfSuppliesServiceInfo == record.data.DescriptionOfSuppliesServices) {
                                count = count + 1;
                            }
                        }
                        if (count > 1) {
                            controller.showMsgTips('Description Of Supplies Services Already exist！');
                            record.data.DescriptionOfSuppliesServices = '';
                        }
                    } else {
                        controller.showMsgTips('Description Of Supplies Services is mandatory .');
                        record.data.DescriptionOfSuppliesServices = record.previousValues.DescriptionOfSuppliesServices;
                    }
                    if (record.modified.DescriptionOfSuppliesServices === '') {
                        var obj = {
                            name: record.data.DescriptionOfSuppliesServices,
                            code: record.data.DescriptionOfSuppliesServices
                        };

                        editor3.getStore().add(obj);
                        editor4.getStore().add(obj);
                        editor6.getStore().add(obj);
                        horizonEditor.getStore().add(obj);
                    } else {
                        //当前修改的DescriptionOfSuppliesServices
                        var beforedss = record.modified.DescriptionOfSuppliesServices;
                        var currentdss = record.get('DescriptionOfSuppliesServices');

                        function changeDss(grid, editor) {
                            var r = editor.getStore().findRecord('code', record.modified.DescriptionOfSuppliesServices);
                            if (r) {
                                r.data.name = record.data.DescriptionOfSuppliesServices;
                                r.data.code = record.data.DescriptionOfSuppliesServices;
                                setTimeout(function () {
                                    editor.setValue(record.data.DescriptionOfSuppliesServices);
                                }, 100);
                            }
                            //联动修改下面所有相同的DescriptionOfSuppliesServices.
                            Ext.each(grid.store.data.items, function (rr) {
                                if (rr.get('DescriptionOfSuppliesServices') == beforedss) {
                                    rr.set('DescriptionOfSuppliesServices', currentdss);
                                }
                            });
                        }

                        changeDss(grid3, editor3);
                        changeDss(grid4, editor4);
                        changeDss(grid6, editor6);
                        changeDss(horizonGrid, horizonEditor);
                    }
                }

                if (record.modified.TotalPrice !== undefined || record.modified.ProjectActivity !== undefined) {
                    var store3 = grid3.getStore();
                    var store4 = grid4.getStore();
                    var pro = record.get('ProjectActivity');

                    if (ukCrossCharge == 'JLRCUK') {

                        for (var i = 0; i < store4.getCount(); i++) {
                            var item4 = store4.getAt(i);
                            var DescriptionOfSuppliesServices = item4.data.DescriptionOfSuppliesServices;
                            var cost = record.data.TotalPrice;

                            if (DescriptionOfSuppliesServices == record.data.DescriptionOfSuppliesServices) {
                                item4.data.ProjectActivity = record.data.ProjectActivity;
                                item4.data.JACost = parseFloat(((cost * item4.data.JASharingRatio) / 100).toFixed(2));
                                item4.data.LRCost = cost - item4.data.JACost;
                            }
                            item4.commit();
                        }
                    } else if (ukCrossCharge == 'UKJLRC' || ukCrossCharge == 'No') {
                        //判断当前修改的DescriptionOfSuppliesServices 是否存在Company Allcation中.
                        var currentExists = store3.data.items.filter(function (rr) {
                            return rr.get('DescriptionOfSuppliesServices') == record.data.DescriptionOfSuppliesServices;
                        }).length > 0;

                        if (currentExists) {
                            //只有 品牌分摊(JLRC) 用到
                            var companyCost = {};

                            for (var i = 0; i < store3.data.items.length; i++) {
                                var item = store3.data.items[i];

                                if (!companyCost[item.get('DescriptionOfSuppliesServices')]) {
                                    companyCost[item.get('DescriptionOfSuppliesServices')] = 0;
                                }

                                if (item.get('ProjectActivity') == record.modified.ProjectActivity && item.get('DescriptionOfSuppliesServices') == record.data.DescriptionOfSuppliesServices) {
                                    item.data.ProjectActivity = record.data.ProjectActivity;
                                }

                                if (record.data.ProjectActivity == item.get('ProjectActivity') && item.get('CompanySharingRatio')) {

                                    if (record.data.DescriptionOfSuppliesServices == item.get('DescriptionOfSuppliesServices')) {
                                        item.data.Cost = (record.data.TotalPrice * item.get('CompanySharingRatio')) / 100;
                                    }

                                    if (!Ext.isEmpty(item.get('ProjectActivity'))) {
                                        var companyval = item.get('Company');
                                        var pro1 = item.get('ProjectActivity');
                                        if (companyval == "JLRC") {
                                            item.data.Balance = controller.balance[pro1] || 0;
                                        } else {
                                            item.data.Balance = 'N/A';
                                        }
                                    }
                                    item.data.budgetControl = controller.budgetControl[pro1];
                                    //第三张表
                                    if (item.get('Company') === 'JLRC') {
                                        companyCost[item.get('DescriptionOfSuppliesServices')] += item.data.Cost;
                                    }
                                }
                                item.commit();
                            }

                            for (var j = 0; j < store4.data.items.length; j++) {
                                var item4 = store4.data.items[j];
                                if (item4.get('DescriptionOfSuppliesServices') == record.data.DescriptionOfSuppliesServices) {
                                    var currentCost = companyCost[item4.get('DescriptionOfSuppliesServices')];
                                    item4.data.ProjectActivity = record.data.ProjectActivity;
                                    item4.data.JACost = parseFloat(((currentCost * item4.data.JASharingRatio) / 100).toFixed(2));
                                    item4.data.LRCost = currentCost - item4.data.JACost;
                                    item4.commit();
                                }
                            }
                        }
                    }
                }
            }
            record.commit();
        } else if (flag == 'add') {
            record.commit();
        }

        //获取当前grid所有的PA,并且拼接成where 语句
        var paSql = [];

        Ext.each(store.data.items, function (rr) {
            paSql.push(" JSON_EXTRACT(t1.name,'$.en') = '" + rr.get('ProjectActivity') + "'");
        });

        Ext.PAIRest.request({
            ns: PAI.application.url,
            url: 'last/dictItemObj/customQuery',
            method: "POST",
            async: false,
            data: {
                "fields": [
                    {
                        "exp": "$." + PAI.Global.getLanguage(),
                        "name": "description",
                        "type": "json"
                    }
                ],
                filter: "t1.pId='a65986df-3037-434f-8825-5db6ebd6fded' and (" + paSql.join(' or ') + ")"
            },
            success: function (result) {
                if (result.responseCode == '100') {
                    var ukApprovers = [];

                    Ext.each(result.data, function (rec) {
                        ukApprovers.push(rec.description);
                    });

                    ref.ukFinanceApprover.setValue(ukApprovers.join(','));
                } else {
                    ref.ukFinanceApprover.setValue('');
                }
            }
        });

    }
}

var amoutCount = [],
    grossAmount = [];

Ext.each(ref.datagrid7.store.data.items, function (record) {
    amoutCount.push(record.get('TotalPrice') || 0);
    grossAmount.push(record.get('GrossAmount') || 0);
});

if (amoutCount.length) {
    ref.pi2.setValue(Ext.util.Format.number(parseFloat(amoutCount.reduce(function (a, b) {
        return (a + b);
    }).toFixed(2)), '0,000.00'));
    ref.tga2.setValue(Ext.util.Format.number(parseFloat(grossAmount.reduce(function (a, b) {
        return (a + b);
    }).toFixed(2)), '0,000.00'));
} else {
    ref.pi2.setValue('0.00');
    ref.tga2.setValue('0.00');
}

function floatAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; }
    try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; }
    m = Math.pow(10, Math.max(r1, r2));
    return parseFloat(((arg1 * m + arg2 * m) / m).toFixed(2));
}